package com.youlai.system.services;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.youlai.utils.DateUtils;
import com.youlai.system.entity.SysEmpEntity;
import com.youlai.system.model.entity.SysDict;
import com.youlai.system.model.query.OrgPageQuery;
import com.youlai.system.repository.SysEmpRepository;
import com.youlai.system.service.SysDictService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysEmpService {

    @Autowired
    private SysEmpRepository repository;

    @Resource
    SysDictService sysDictService;

    /**
     * 分页查询列表
     *
     * @param queryParams
     * @return
     */
    public Page<SysEmpEntity> getPage(OrgPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();
        DateUtils.toDatabaseFormat(queryParams, "startUpdateTime", "endUpdateTime");

        //Sort sort =  Sort.by(Sort.Direction.DESC,"updateTime");   // .and(Sort.by("createTime").descending());
        Pageable pageable = PageRequest.of(pageNum-1, pageSize, Sort.Direction.DESC, "updateTime");
        Page<SysEmpEntity> page = repository.findAll(pageable);

        // 数据字典项
        List<SysDict> dictList = sysDictService.list(new LambdaQueryWrapper<SysDict>()
                .eq(SysDict::getTypeCode, "empType")
                .select(SysDict::getValue, SysDict::getName)
        );
        Map<String,String> orgTypeMap =  dictList.stream().collect(Collectors.toMap(SysDict::getValue,SysDict::getName));

        for(SysEmpEntity o:page) {
            //o.setOrgTypeName(IBaseEnum.getLabelByValue(o.getOrgType(), com.youlai.system.common.enums.GenderEnum.class));
            o.setEmpTypeName(orgTypeMap.get(String.valueOf(o.getEmpType())));
        }
        return page;
    }

    public void saveOrUpdate(SysEmpEntity entity){
        repository.save(entity);
    }

    public SysEmpEntity findById(Long id){
        Optional<SysEmpEntity> optional  = repository.findById(id);
        if(optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    public Boolean deleteAllById(String ids){
        List<String> list = Arrays.stream(ids.split(",")).toList();
        for(String s:list) {
            repository.deleteById(Long.valueOf(s));
        }
        return true;
    }

    public List<SysEmpEntity> findByEmpName(String empName){
        return repository.findByEmpName(empName);
    }

}


